package com.aixuexiao.web.controller;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.aixuexiao.model.Message;
import com.aixuexiao.model.Reply;
import com.aixuexiao.service.WeixinService;
import com.aixuexiao.util.WeixinUtil;
import com.weixin.sdk.model.reply.Article;
import com.weixin.sdk.model.reply.NewsMessage;
import com.weixin.sdk.util.MessageUtil;

@Controller()
public class WeixinController {
	
	private static final String TOKEN = "employee";
	
	public static int pagesize = 10;
	
	@Resource(name="weixinService")
	private WeixinService weixinService;
	
	//接收微信公众号接收的消息，处理后再做相应的回复
	@RequestMapping(value="/weixin",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String replyMessage(HttpServletRequest request){
		//仅处理微信服务端发的请求
		if (checkWeixinReques(request)) {
			Map<String, String> requestMap = WeixinUtil.parseXml(request);
			Message message = WeixinUtil.mapToMessage(requestMap);
			//weixinService.addMessage(message);//保存接受消息到数据库
			String type = message.getMsgType();
			if (type.equals(Message.TEXT)) {//仅处理文本回复内容
				String content = message.getContent();//消息内容
				NewsMessage newsMessage = new NewsMessage();  
                newsMessage.setToUserName(message.getFromUserName());  
                newsMessage.setFromUserName(message.getToUserName());  
                newsMessage.setCreateTime(new Date().getTime());  
                newsMessage.setMsgType("news");  
                newsMessage.setFuncFlag(0);  
				if("留言反馈".equals(content) ){
					List<Article> articleList = new ArrayList<Article>(); 
					Article article = new Article();  
                    article.setTitle("留言反馈");  
                    article.setDescription("");  
                    article.setPicUrl(getDomain()+"/assets/images/btn_liuyan.jpg");  
                    article.setUrl(getDomain()+"/liuyan?openid="+message.getFromUserName());  
                    articleList.add(article);  
                    // 设置图文消息个数  
                    newsMessage.setArticleCount(articleList.size());  
                    // 设置图文消息包含的图文集合  
                    newsMessage.setArticles(articleList);  
                    // 将图文消息对象转换成xml字符串  
                    return MessageUtil.newsMessageToXml(newsMessage);  
				}else if("员工认证".equals(content)){
					List<Article> articleList = new ArrayList<Article>(); 
					Article article = new Article();  
                    article.setTitle("员工认证");  
                    article.setDescription("");  
                    article.setPicUrl(getDomain()+"/assets/images/LOGO_1.png");  
                    article.setUrl(getDomain()+"?openid="+message.getFromUserName());  
                    articleList.add(article);  
                    // 设置图文消息个数  
                    newsMessage.setArticleCount(articleList.size());  
                    // 设置图文消息包含的图文集合  
                    newsMessage.setArticles(articleList);  
                    // 将图文消息对象转换成xml字符串  
                    return MessageUtil.newsMessageToXml(newsMessage);  
				}else if("在线申请".equals(content)){
					List<Article> articleList = new ArrayList<Article>(); 
					Article article = new Article();  
                    article.setTitle("文体俱乐部");  
                    article.setDescription("");  
                    article.setPicUrl("http://www.henro.cn/uploads/f/frbeev1454049984/4/8/1/0/56ece1278615e.jpg");  
                    article.setUrl(getDomain()+"/companyclub?openid="+message.getFromUserName());  
                    articleList.add(article);  
                    // 设置图文消息个数  
                    newsMessage.setArticleCount(articleList.size());  
                    // 设置图文消息包含的图文集合  
                    newsMessage.setArticles(articleList);  
                    // 将图文消息对象转换成xml字符串  
                    return MessageUtil.newsMessageToXml(newsMessage);  
				}else if("文体俱乐部".equals(content)){
					List<Article> articleList = new ArrayList<Article>(); 
					Article article = new Article();  
                    article.setTitle("文体俱乐部");  
                    article.setDescription("");  
                    article.setPicUrl("http://www.henro.cn/uploads/f/frbeev1454049984/4/8/1/0/56ece1278615e.jpg");  
                    article.setUrl(getDomain()+"/companyclub?openid="+message.getFromUserName());  
                    articleList.add(article);  
                    // 设置图文消息个数  
                    newsMessage.setArticleCount(articleList.size());  
                    // 设置图文消息包含的图文集合  
                    newsMessage.setArticles(articleList);  
                    // 将图文消息对象转换成xml字符串  
                    return MessageUtil.newsMessageToXml(newsMessage);  
				}else if("积分签到".equals(content)){
					List<Article> articleList = new ArrayList<Article>(); 
					Article article = new Article();  
                    article.setTitle("积分签到");  
                    article.setDescription("");  
                    article.setPicUrl(getDomain()+"/assets/images/qiandao_wx.png");  
                    article.setUrl(getDomain()+"/qiandaopage?openid="+message.getFromUserName());  
                    articleList.add(article);  
                    // 设置图文消息个数  
                    newsMessage.setArticleCount(articleList.size());  
                    // 设置图文消息包含的图文集合  
                    newsMessage.setArticles(articleList);  
                    // 将图文消息对象转换成xml字符串  
                    return MessageUtil.newsMessageToXml(newsMessage);  
				}
					
			}
		}
		return Reply.WELCOME_CONTENT;
	}
	
	
	//微信公众平台验证url是否有效使用的接口
	@RequestMapping(value="/weixin",method=RequestMethod.GET,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String initWeixinURL(HttpServletRequest request){
		String echostr = request.getParameter("echostr");
		if (checkWeixinReques(request) && echostr != null) {
			return echostr;
		}else{
			return "error";
		}
	}
	
	
	/**
	 * 根据token计算signature验证是否为weixin服务端发送的消息
	 */
	private static boolean checkWeixinReques(HttpServletRequest request){
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		if (signature != null && timestamp != null && nonce != null ) {
			String[] strSet = new String[] { TOKEN, timestamp, nonce };
			java.util.Arrays.sort(strSet);
			String key = "";
			for (String string : strSet) {
				key = key + string;
			}
			String pwd = WeixinUtil.sha1(key);
			return pwd.equals(signature);
		}else {
			return false;
		}
	}
	
	/**
	 * 收到消息列表页面
	 */
	@RequestMapping(value="/manager/messages",method=RequestMethod.GET)
	public ModelAndView listMessage(String pagenum){
		ModelAndView mv=new ModelAndView();
		mv.addObject("sidebar","messages");
		mv.setViewName("messages");
		int num = 1;
		if(null!=pagenum){
			num = Integer.parseInt(pagenum);
		}
		List<Message> list = weixinService.listMessage((num-1)*pagesize, pagesize);
		mv.addObject("messageList", list);
		mv.addObject("pagenum", num);
		mv.addObject("length", list.size());
		return mv;
	}
	
	
	/**
	 * 回复消息列表页面
	 */
	@RequestMapping(value="/manager/replys",method=RequestMethod.GET)
	public ModelAndView listReply(String pagenum){
		ModelAndView mv=new ModelAndView();
		mv.addObject("sidebar","replys");
		mv.setViewName("replys");
		int num = 1;
		if(null!=pagenum){
			num = Integer.parseInt(pagenum);
		}
		List<Reply> list = weixinService.listReply((num-1)*pagesize, pagesize);
		mv.addObject("replyList", list);
		mv.addObject("pagenum", num);
		mv.addObject("length", list.size());
		return mv;
	}
	
	private String getDomain(){
		return "http://cnvxt.net:8080/employee";
	}
	
}
